package com.guli.generator.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.guli.exceptionhandler.GuliException;
import com.guli.generator.mapper.EduSubjectMapper;
import com.guli.generator.pojo.EduSubject;
import com.guli.generator.ulits.Subject;

public class SubjectListener extends AnalysisEventListener<Subject> {


    private EduSubjectMapper subjectMapper;
    public SubjectListener(){}
    public SubjectListener(EduSubjectMapper subjectMapper){
        this.subjectMapper=subjectMapper;
    }
    @Override
    public void invoke(Subject subject, AnalysisContext analysisContext) {
        if(subject==null){
            throw new GuliException(20001,"文本为空");
        }
        EduSubject eduSubject = getEduSubject(subject.getOneTitle());
        if(eduSubject==null){
            eduSubject=new EduSubject();
            eduSubject.setTitle(subject.getOneTitle());
            subjectMapper.insert(eduSubject);
        }
        String paId = eduSubject.getId();
        EduSubject towSubject = getTowSubject(subject.getTowTitle(), paId);
        if(towSubject==null){
            towSubject=new EduSubject();
            towSubject.setTitle(subject.getTowTitle());
            towSubject.setParentId(paId);
            subjectMapper.insert(towSubject);
        }
    }
    private EduSubject getEduSubject(String name){
        QueryWrapper<EduSubject> wrapper =new QueryWrapper<>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id","0");
        EduSubject eduSubject = subjectMapper.selectOne(wrapper);
        return eduSubject;
    }
    private EduSubject getTowSubject(String name,String paId){
        QueryWrapper<EduSubject> wrapper =new QueryWrapper<>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id",paId);
        EduSubject eduSubject = subjectMapper.selectOne(wrapper);
        return eduSubject;
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
